package com.demo.phonerepair.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.phonerepair.mapper.ManagementMapper;
import com.demo.phonerepair.mapper.RepairMapper;
import com.demo.phonerepair.mapper.UserMapper;
import com.demo.phonerepair.module.ManagementCreateDTO;
import com.demo.phonerepair.module.ManagementUpdateDTO;
import com.demo.phonerepair.pojo.Management;
import com.demo.phonerepair.pojo.Repair;
import com.demo.phonerepair.pojo.User;
import com.demo.phonerepair.service.ManagementService;
import com.demo.phonerepair.util.Md5Password;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ManagementServiceImpl extends ServiceImpl<ManagementMapper,Management> implements ManagementService {
    @Autowired
    private ManagementMapper managementMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RepairMapper repairMapper;

    private static final List<String> VALID_PAYMENT_STATUS = Arrays.asList("待文付", "支付中", "支付完成", "支付异常");

    @Override
    public Map<String, Object> getAllManagement(
            Integer userId, String userRole, String searchKeyword,
            Integer pageNum, Integer pageSize, String sortField,
            String sortOrder) {
        if (pageNum == null)
            pageNum = 1;
        if (pageSize == null)
            pageSize = 10;
        if (sortField == null)
            sortField = "createAt";
        if (sortOrder == null)
            sortOrder = "desc";
        if (searchKeyword == null)
            searchKeyword = "";
        Page<Management> page = new Page<>(pageNum, pageSize);
        IPage<Management> pageResult = managementMapper.selectAllRepairManagement(
                page,
                userId,
                searchKeyword,
                sortField,
                sortOrder
        );
        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("count", pageResult.getTotal());
        responseMap.put("repairManagementList", pageResult.getRecords());
        return responseMap;
    }

    @Override
    public Boolean deleteRepair(Integer repairId, Integer userId, String password) {
//做参数校验
        if (repairId == null || userId == null || password == null)
            return false;//根据userId获取对象
        User user = userMapper.selectById(userId);
        if (user == null)
            return false;
        if (!Md5Password.generateMD5(password).equals(user.getUserPasswordHash()))
            return false;

        Integer deleteCount = managementMapper.deleteById(repairId);
        return deleteCount > 0 ? true : false;//返回结果给Controller
    }

    @Override
    public Boolean createRepairManagement(ManagementCreateDTO createDTO) {
        //做参数的非空校验
        if (createDTO.getRepairRequestId() == null
                || createDTO.getRepairNotes() == null
                || createDTO.getTechnicianId() == null)
            return false;
        //判断订单id是否存在Request的表中
        Repair repair = repairMapper.selectById(createDTO.getRepairRequestId());
        if (repair == null)
            return false;
        //DTO转实体类
        Management management = new Management();
        management.setRepairRequestId(createDTO.getRepairRequestId());
        management.setTechnicianId(createDTO.getTechnicianId());
        management.setRepairNotes(createDTO.getRepairNotes());
        management.setRepairPrice("100");
        management.setPaymentStatus("待支付");
        management.setCreatedAt(LocalDateTime.now());
        management.setUpdatedAt(LocalDateTime.now());
        return this.save(management);
    }

    @Override
    public Boolean updateRepairManagement(ManagementUpdateDTO updateDTO) {
//做参数校验，校验订单ID
        if (updateDTO.getRepairId() == null)
            return false;
        if (updateDTO.getRepairPrice() == null)
            return false;
//如果支付状态不是VALID_PAYMENT_STATUS中的一种，则返回false
        if (!VALID_PAYMENT_STATUS.contains(updateDTO.getPaymentStatus()))
            return false;//维修描述不能为空
        if (updateDTO.getRepairNotes() == null)
            return false;
//技术人员不能为空
        if (updateDTO.getTechnicianId() == null)
            return false;
//判断 user表中是否存在该ID
        User technician = userMapper.selectById(updateDTO.getTechnicianId());
        if (technician == null)
            return false;
//构建更新对象
        Management management = new Management();
        management.setRepairId(updateDTO.getRepairId());
        management.setRepairPrice(updateDTO.getRepairPrice().toString());
        management.setPaymentStatus(updateDTO.getPaymentStatus());
        management.setRepairNotes(updateDTO.getRepairNotes());
        management.setTechnicianId(updateDTO.getTechnicianId().toString());
        management.setUpdatedAt(LocalDateTime.now());
//调用MybatisPlus的updateById方法
        int updateCount = managementMapper.updateById(management);
        return updateCount > 0;
    }
}
